<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\exception\ValidateException;
use think\facade\Filesystem;
use think\facade\Request;

class Index
{
    public function index()
    {
        $path = app()->getRootPath();
        $has_file = file_exists($path . '/' .'.lock');
        if($has_file){
            return redirect((string)url('/dist/'));
        } else {
            return redirect((string)url('/install/'));
        }
    }


    /**
     * 安装数据库，修改系统配置
     * @return \think\response\Json
     */
    public function install(){
        $data = json_decode(file_get_contents("php://input"),true);
        try {
            // 连接数据库
            $data['db_port'] = $data['db_port'] ? (int)$data['db_port'] : 3306;
            $mysqli = new \mysqli($data['db_server'],$data['db_user'],$data['db_pwd'],null,$data['db_port']);
            if (mysqli_connect_errno()) {
                return json(['status'=>201,'msg'=>'连接数据库失败，请检查服务器地址和用户名密码']);
            }
            mysqli_set_charset($mysqli, 'utf8mb4');

            // 创建数据库
            if($data['db_new'] == 0){
                if(self::check_db_not_exists($mysqli,$data)){
                    $create_db = "CREATE DATABASE IF NOT EXISTS ".$data['db_name']." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
                    $mysqli->query($create_db);
                } else {
                    return json(['status'=>201,'msg'=>'数据库已经存在，请删除数据库或者，修改数据库名称！']);
                }
            } else {
                $drop_db = "DROP DATABASE ".$data['db_name'].";";
                $mysqli->query($drop_db);
                $create_db = "CREATE DATABASE ".$data['db_name']." DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
                $mysqli->query($create_db);
            }

            // 导入数据
            self::importData($mysqli,$data);

            // 生成配置文件
            self::getEnv($data);

            // 生成前端development环境文件
            self::get_env_development();

            // 生成安装完成的标记文件

            $file = app()->getRootPath().'.lock';
            $handle = fopen($file,'w');
            fwrite($handle,'');
            fclose($handle);

        } catch (\Exception $e){
            return json(['status'=>202,'msg'=>$e->getMessage()]);
        }
        return json(['status'=>200,'msg'=>'安装完成！']);
    }


    private function importData($mysqli,$data){
        try {
            $path = app()->getRootPath();
            $sql_file = $path . '/data.sql';
            $sql = file_get_contents($sql_file);
            // 数据库创建是否成功
            $use_db_result = $mysqli->query("USE ".$data['db_name'].';');
            if(!$use_db_result){
                throw new ValidateException('请检查数据库名是否合法后，再重试！');
            }
            // 执行脚本内容
            $result = $mysqli->multi_query($sql);
            if(!$result){
                throw new ValidateException('数据导入出现错误！');
            }
            return true;
        } catch (\Exception $e){
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 生成配置文件
     * @param $data
     * @return bool
     */
    private function getEnv($data){
        try {
            $path = app()->getRootPath();
            // 创建数据库配置文件
            $host = $data['db_server'];
            $dbname = $data['db_name'];
            $user = $data['db_user'];
            $pwd = $data['db_pwd'];
            $port = $data['db_port'];
            $content = "
APP_DEBUG = true

[APP]
DEFAULT_TIMEZONE = Asia/Shanghai

[DATABASE]
TYPE = mysql
HOSTNAME = $host
DATABASE = $dbname
USERNAME = $user
PASSWORD = $pwd
HOSTPORT = $port
CHARSET = utf8
DEBUG = true

[LANG]
default_lang = zh-cn";
            ob_start();
            echo $content;
            $_cache=ob_get_contents();
            ob_end_clean();

            if($_cache){
                $file = $path.'.env';
                $handle = fopen($file,'w');
                fwrite($handle,$_cache);
                fclose($handle);
            }
            return true;
        } catch (\Exception $e){
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 检查数据库是否存在
     * @param $mysqli
     * @param $data
     * @return bool
     */
    private function check_db_not_exists($mysqli,$data){
        try {
            $result = $mysqli->query('show databases;');
            $databases_list = $result->fetch_all(MYSQLI_BOTH);
            $database_array = [];
            foreach ($databases_list as $v){
                array_push($database_array,$v['Database']);
            }
            if(!in_array($data['db_name'],$database_array)){
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e){
            return false;
        }

    }

    /**
     * 根据当前访问的虚拟主机的域名，确定开发时的后端服务器接口地址
     * @return bool
     */
    private function get_env_development(){
        if (
            (! empty($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] == 'https') || 
            (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || 
            (! empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') 
        ){
            $_SERVER['REQUEST_SCHEME'] = 'https';
        } else {
            $_SERVER['REQUEST_SCHEME'] = 'http';
        }
        $server_protocol = $_SERVER['REQUEST_SCHEME'];
        $server_name = input('server.SERVER_NAME');
        $server_port = input('server.SERVER_PORT');
        if(in_array($server_name,['0.0.0.0','127.0.0.1','localhost'])){
            $server_protocol = 'http';
            $server_name = '127.0.0.1';
        }
        if($server_port != 80){
            $server_port = ':' . $server_port;
        }else{
            $server_port = '';
        }
        $url = $server_protocol . "://" . $server_name . $server_port;
        $content = "
module.exports = {
    devServer: {
        host: '0.0.0.0',
        port: 3333,
        open: true,
        disableHostCheck: true,
        proxy: {
            '/admin': {
                target: '$url/admin',
                changeOrigin: true,
                pathRewrite: {
                    '/admin': '/'
                }
            },
            '/uploads': {
                target: '$url/uploads',
                changeOrigin: true,
                pathRewrite: {
                    '/uploads': '/'
                }
            },
            '/api': {
                target: '$url/api',
                changeOrigin: true,
                pathRewrite: {
                    '/api': '/'
                }
            }
        }
    },
    outputDir: '../public/dist',
    assetsDir: 'static',
    productionSourceMap: false,
    parallel: false,
    publicPath: './'
}
";
        try {
            $path = app()->getRootPath();
            ob_start();
            echo $content;
            $_cache=ob_get_contents();
            ob_end_clean();
            if($_cache){
                $file = $path.'/ui/vue.config.js';
                $handle = fopen($file,'w');
                fwrite($handle,$_cache);
                fclose($handle);
            }
            return true;
        } catch (\Exception $e){
            throw new ValidateException($e->getMessage());
        }
    }
}
